package com.lyubia.shop.manager.service.impl;

import com.lyubia.shop.common.result.FileResult;
import com.lyubia.shop.manager.service.FileUploadService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${qiniu.ak}")
    private String ak;

    @Value("${qiniu.sk}")
    private String sk;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public FileResult fileUpload(InputStream is, String fileName) {
        FileResult fileResult = new FileResult();
        try {
            Configuration configuration = new Configuration(Region.region2());
            UploadManager uploadManager = new UploadManager(configuration);
            Auth auth = Auth.create(ak, sk);
            String token = auth.uploadToken(bucket);
            Response response = uploadManager.put(is, fileName, token, null, null);
            System.out.println(response.isOK());
            if (response.isOK()) {
                fileResult.setSuccess("上传成功");
                fileResult.setMsg("上传成功");
                fileResult.setFileUrl(domain + fileName);
            }
        } catch (QiniuException e) {
            Response response = e.response;
            System.err.println(response.toString());
            fileResult.setError("文件上传失败!");
        }
        return fileResult;
    }
}
